<template>
  <el-dialog v-if="load" :close-on-click-modal="false" title="活动类型配置" v-model="visible" class="full" align-center
    width="1200px" @close="handleClose">
    <div class="pt-3 h-full">
      <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <el-input v-model="form.promotion_name" placeholder="活动名称" class="w-36" clearable></el-input>
        <VSelect v-model="form.platform_id" placeholder="活动平台" type="platforms" multiple collapse-tags filterable
          clearable style="min-width: 160px" />
        <VCascader v-model="form.update_user_id" placeholder="更新人" multiple collapse-tags filterable clearable
          style="min-width: 160px" />
        <VGroup>
          <div class="v-group-item">更新时间</div>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <el-button type="primary" @click="handleRow('add')"><i class="dk-iconfont icon-Plus" />添加</el-button>
        <el-button type="danger" @click="handleBatch('delete')"><i class="dk-iconfont icon-Delete" />删除</el-button>
      </template>
    </VTable>
    </div>
    <Add ref="addRef" :options="options" @success="query" />
    <VLog ref="logRef" />
  </el-dialog>
</template>

<script setup lang="jsx">
import api from './api'
import Add from './Add'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const baseName = 'promotion_config'
const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const tableRef = ref()
// 查询
const query = () => {
  tableRef?.value.query()
}


// 批量操作
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const pc_ids = selection.map(d => d.pc_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    delete: () => {
      ElMessageBox.confirm('是否确认删除？', '提示', {
        confirmButtonClass: 'messagebox-confirm-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.delete({ pc_ids }).then(res => {
            ElMessage.success('操作成功')
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
  }
  handle[name]()
}
// 单行操作
const addRef = ref()
const logRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { pc_id } = row || {}
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    add: () => {
      addRef?.value.open()
    },
    edit: () => {
      addRef?.value.open(pc_id)
    },
    delete: () => {
      ElMessageBox.confirm('是否确认删除？', '提示', {
        confirmButtonClass: 'messagebox-confirm-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading('delete')
          api.delete({ pc_ids: [pc_id] }).then(res => {
            ElMessage.success('操作成功')
            query()
          }).finally(() => closeLoading('delete'))
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, pc_id })
    }
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  size: 'small',
  rowConfig: { height: 'auto' },
  showHeaderOverflow: false,
  formConfig: {
    data: {
      dateRange: { type: 'update_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', fixed: 'left', width: 40 },
    { field: 'promotion_name', title: '活动名称', minWidth: 100 },
    {
      field: 'warehouse', title: '活动时间', minWidth: 166, slots: {
        default: ({ row }) => `${row.promotion_start_time}-${row.promotion_end_time}`
      }
    },
    { field: 'platform_name', title: '活动平台', minWidth: 100 },
    { field: 'attribute_name', title: '产品分类', minWidth: 100 },
    { field: 'remark', title: '备注', minWidth: 100 },
    { field: 'update_user', title: '更新人', minWidth: 100 },
    { field: 'update_time', title: '更新时间', minWidth: 150 },
    {
      title: '操作', width: 150, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { audit_status } = row
          // 审核状态 1待提交 2待审核 3已审核 4已驳回 5已作废
          return <div>
            <el-button link type="primary" onClick={() => handleRow('edit', row)}>修改</el-button>
            <el-button link type="danger" onClick={() => handleRow('delete', row, rowIndex)}>删除</el-button>
            <el-button link type="primary" onClick={() => handleRow('log', row)}>日志</el-button>
          </div>
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page })
    }
  }
})

const emit = defineEmits(['close', 'change'])

// 打开弹窗
const open = async () => {
  if (!load.value) {
    load.value = true
  }
  loadings = reactive({})
  visible.value = true
  nextTick(() => {
    tableRef.value.resetAndQuery()
  })
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}

defineExpose({ open })
</script>